﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Collections;

namespace BeerScanOTron_Barcode
{
    public partial class ScannerMain : Form
    {
        private string _barcode;

        public ScannerMain()
        {
            InitializeComponent();
            //LoadData();
        }

        private void LoadData()
        {
            using (ScanOTronDB ctx = new ScanOTronDB())
            {
                List<UserInfo> data = ctx.Drinkers.Select(u => new UserInfo
                {
                    BadgeID = u.CardId,
                    FirstName = u.FirstName,
                    LastName = u.LastName,
                    DrinkCount = ctx.DispenserInfoes.Where(d => d.CardId == u.CardId && d.ServeDate == DateTime.Today).Count()
                }).ToList();

                dgvMain.DataSource = data;
            }
        }

        private void ScannerMain_KeyDown(object sender, KeyEventArgs e)
        {
            // We have to check for null barcode because of weird behavior on scanning to close user detail dlg
            // returning a Keys.Return.
            if (_barcode != null && e.KeyCode == Keys.Return)
            {
                ProcessCompleteBarcode();

                // Reset scan buffer.
                _barcode = null;
            }
            else
            {
                // Add non-control characters to scan buffer.
                if (char.IsLetterOrDigit((char)e.KeyCode))
                {
                    _barcode += e.GetKeyValue();
                }
            }
        }

        private void ProcessCompleteBarcode()
        {

            using (UserDetail dlg = new UserDetail(_barcode))
            {
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    LoadData();
                }
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

    }
}
